<template>
	<view class="container">
    <uni-forms :modelValue="formData" ref="regRef" validateTrigger="blur">
		<uni-section title="课堂时间分配">
      <uni-forms-item label="任课教师讲授时间（分钟）"  required name="teachTime">
        <uni-easyinput type="digit" v-model="formData.teachTime" placeholder="请输入任课教师讲授时间" />
      </uni-forms-item>
      <uni-forms-item label="师生互动/发言时间（分钟）"  required name="interactionTime">
        <uni-easyinput type="digit" v-model="formData.interactionTime" placeholder="请输入师生互动/发言时间" />
      </uni-forms-item>
		</uni-section>
    <!--教材使用情况-->
		<uni-section title="教材使用情况">
      <uni-forms-item label="任课教师选用教材及本次课授课内容"  required >
        <uni-data-checkbox v-model="formData.bookTeacherUseRate"  :localdata="bookTeacherUseType" />
      </uni-forms-item>

      <uni-forms-item label="学生持有教材情况"  required >
        <uni-data-checkbox v-model="formData.bookStudentUseRate"  :localdata="bookStudentUseType" />
      </uni-forms-item>
		</uni-section>
		<uni-section title="课堂授课类型">
			<view class="example">
        <!--授课类型复选框-->
        <uni-data-checkbox multiple v-model="formData.teachType"  :localdata="teachType" />
				<uni-forms-item label="其他课堂授课类型">
					<uni-easyinput type="string" v-model="formData.otherTeachType" placeholder="请填写其他授课类型" />
				</uni-forms-item>
			</view>
		</uni-section>
		<uni-section title="课堂教学存在的问题、给出的建议或者值得推广之处">
      <uni-forms-item label="教学存在的问题">
        <uni-easyinput type="textarea" v-model="formData.improve" placeholder="请填写教学存在的问题（评价等级为C类必填，其他等级选填）" />
      </uni-forms-item>
      <uni-forms-item label="给出提升教学质量的切实可行的建议">
        <uni-easyinput type="textarea" v-model="formData.suggestion" placeholder="请填写给出提升教学质量的切实可行的建议（评价等级为C类和B类必填，其他等级选填）" />
      </uni-forms-item>
      <uni-forms-item label="本教学课堂值得推广之处">
        <uni-easyinput type="textarea" v-model="formData.recommend" placeholder="请填写本教学课堂值得推广之处（评价等级为A类必填，其他等级选填）" />
      </uni-forms-item>
      <uni-forms-item label="听课记录本照片" required>
        <view class="container">
          <!-- 若有图片路径，显示图片 -->
          <image v-if="recordImg" :src="recordImg" mode="aspectFit"></image>
          <!-- 拍照按钮 -->
          <button @click="takePhoto">拍照</button>
        </view>
      </uni-forms-item>
		</uni-section>
		<view class="example btn_submit">
			<button type="primary" @click="goProStage()">提交</button>
		</view>
    </uni-forms>
		<message :msg="showMsg"></message>
	</view>
</template>

<script>
import {getToken, isLogin} from '@/../utils/auth';
import { teachType,bookStudentUseType,bookTeacherUseType } from '@/../utils/enums';
import {addSummary} from "@/api/eval";
import message from '../../component/message.vue';

export default {
	onLoad: function(option) {
		isLogin(this);
		this.teachType = teachType;
		this.bookStudentUseType = bookStudentUseType;
		this.bookTeacherUseType = bookTeacherUseType;
	},
  onReady() {
    this.$refs.regRef.setRules(this.formRules);
  },
  onBackPress() {
    // 在这里编写自定义的返回逻辑
    console.log('自定义返回逻辑触发');
    // 可以在这里执行一些其他操作，比如提示用户确认返回
    uni.showModal({
      title: '提示',
      content: '评价未完成，返回将重新进行评价，确定要返回吗？',
      confirmColor:"#e8380d",
      success: (res) => {
        if (res.confirm) {
          // 用户点击确定，执行默认返回操作
          uni.navigateTo({
            url: `/pages/eval/index`
          })
        }
      }
    });
    // 返回 true 表示阻止默认返回行为，返回 false 表示允许默认返回行为
    return true;
  },
  created() {
    // 从传参中获取recordId
    this.formData.recordId = this.$route.query.recordId;
    if(this.formData.recordId === null || this.formData.recordId === undefined){
      uni.showToast({
        title: '请先选择课程',
        icon: 'error',
        duration: 2000,
        complete: function () {
          // 跳转选择课程页面
          uni.redirectTo({
            url: `/pages/eval/index`,
          })
        }
      });
    }
    // 上一步骤选择的评价等级
    this.scoreLevel = this.$route.query.recordId;
    // 上一步骤选择的评分
    this.score = this.$route.query.score;
  },
  data() {
		return {
      teachType:[],
      bookStudentUseType:[],
      bookTeacherUseType:[],
      scoreLevel:null,
      score:null,
			showMsg: {},
			messageText: '',
			msgType: '',
      recordImg:'',
			formData: {
        recordId: null,
        teachType: [],
        otherTeachType: null,
        bookStudentUse: null,
        bookStudentUseRate: null,
        bookTeacherUse: null,
        bookTeacherUseRate: null,
        teachTime: null,
        interactionTime: null,
        improve: null,
				suggestion: null,
        recommend: null,
        recordImg:null
			},
      formRules: {
        teachTime: {
          rules: [{
            required: true,
            errorMessage: " ",
          }]
        },
        interactionTime: {
          rules: [{
            required: true,
            errorMessage: " ",
          }]
        },
      }
		}
	},
	components: {
		message,
	},
	methods: {
    // 拍照方法
    takePhoto() {
      const _that = this;
      uni.chooseImage({
        count: 1, // 最多选择 1 张图片
        sourceType: ['camera'], // 只允许使用相机拍照
        success: (res) => {
          console.log(res)
          // 上传图片
          this.uploadPhoto(res.tempFilePaths[0],_that);
        },
        fail: (err) => {
          console.error('拍照失败:', err);
        }
      });
    },
    // 上传图片方法
    uploadPhoto(imageTempPath,_that) {
      if (!imageTempPath) {
        return;
      }
      uni.uploadFile({
        url: process.env.VUE_APP_BASE_API+"/common/upload?filePath=teachRecordImg", // 替换为实际的服务器上传接口地址
        header: {
          Authorization: "Bearer " + getToken(),
        },
        filePath: imageTempPath,
        name: 'file', // 服务器接收文件的字段名
        success: (res) => {
          if (res.statusCode === 200) {
            uni.showToast({
              title: '上传成功',
              icon: 'success'
            });
            const resObj = JSON.parse(res.data);
            _that.formData.recordImg = resObj.fileName;
            _that.recordImg = process.env.VUE_APP_BASE_API+resObj.fileName;
          } else {
            console.error('上传失败:', res.errMsg);
            uni.showToast({
              title: '上传失败',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          console.error('上传失败:', err);
          uni.showToast({
            title: '上传失败',
            icon: 'none'
          });
        }
      });
    },
		goProStage: function() {
      //判断是否登录
      if (!isLogin(this)) {
        return;
      }
      // 表单必填项验证
      this.$refs.regRef.validate().then(res => {
        console.log(res)
        // 验证--教研本照片
        if(this.formData.recordImg == "" && this.formData.recordImg === null){
          uni.showToast({
            title: '请上传教研本照片',
            duration: 2000
          });
          return;
        }
        // 验证--教材使用情况
        if(this.formData.bookTeacherUseRate === null || this.formData.bookStudentUseRate === null){
          uni.showToast({
            title: '请对教材使用情况进行选择',
            duration: 2000
          });
          return;
        }
        // 验证--课堂授课类型
        if(this.formData.teachType.length == 0 && this.formData.otherTeachType === null){
          uni.showToast({
            title: '请选择教师授课类型',
            duration: 2000
          });
          return;
        }
        // 验证--课堂建议
        if(this.score >= 95 && this.formData.recommend === null){
          uni.showToast({
            title: '请填写课程亮点',
            duration: 2000
          });
          return;
        }
        if(this.score < 75 && this.formData.improve === null){
          uni.showToast({
            title: '请填写课堂不足',
            duration: 2000
          });
          return;
        }
        // 教学类型，若选择了多个用逗号分隔
        if(this.formData.teachType.length >0){
          this.formData.teachType = this.formData.teachType.join(',');
        }
        // 教材使用情况文字说明
        const bookStudentUseOption =  this.bookStudentUseType.find(opt => opt.value == this.formData.bookStudentUseRate);
        this.formData.bookStudentUse = bookStudentUseOption.text;
        const bookTeacherUseOption =  this.bookTeacherUseType.find(opt => opt.value == this.formData.bookTeacherUseRate);
        this.formData.bookTeacherUse = bookTeacherUseOption.text;
        // 请求接口提交表单
        addSummary(this.formData).then(response => {
          // 显示成功提示
          uni.showToast({
            title: '提交成功',
            icon: 'success',
            duration: 2000,
            complete: function () {
              // 跳转成功页面
              uni.redirectTo({
                url: `/pages/eval/success`
              })
            }
          });
        });
      });
		},
	}
}
</script>

<style lang="scss">
	.segmented-control {
		margin-bottom: 15px;
	}

	.button-group {
		margin-top: 15px;
		display: flex;
		justify-content: space-around;
	}

	.form-item {
		display: flex;
		align-items: center;
	}

	.button {
		display: flex;
		align-items: center;
		height: 35px;
		margin-left: 10px;
	}
	.uni-forms-item {
		margin-bottom: 10px !important;
	}
	.btn_submit {
		padding-bottom: 30px;
	}
  /* 为每个复选框容器设置宽度，使其三个一组 */
  .score-level-container .checklist-box {
    width: calc(100% / 3) !important;
    padding: 5px; /* 可选，添加内边距使布局更美观 */
  }
</style>